<?php
namespace app\warehouse\admin;
use app\system\admin\Admin;
use app\warehouse\model\Warehouse as WarehouseModel;
use app\system\model\SystemUser as SystemUserModel;
use app\shop\model\Shop as ShopModel;
use app\warehouse\model\Stock as StockModel;
use app\warehouse\model\Allocation as AllocationModel;
use app\product\model\Product as ProductModel;
use think\Db;
class Allocation extends Admin
{
    protected $hisiModel = 'Allocation';//模型名称[通用添加、修改专用]
    protected $hisiTable = '';//表名称[通用添加、修改专用]
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function index()
    {

        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $a_warehouse      = $this->request->param('a_warehouse/d', '');
            $b_warehouse      = $this->request->param('b_warehouse/d', '');

            $status      = $this->request->param('status/d', '');
            $start      = $this->request->param('start', '2000-01-01');
            $end      = $this->request->param('end', date('Y-m-d H:i:s',time()));

            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d H:i:s',time());
            }
            if(!empty($status)){
                $where['status'] = $status;
            }

            if(!empty($a_warehouse)){
                $where['a_warehouse'] = $a_warehouse;
            }
            if(!empty($b_warehouse)){
                $where['b_warehouse'] = $b_warehouse;
            }
            if($this->request->param('operation') == 2){
                $xxx = AllocationModel::where($where)
                ->field('*, a_shop as a_shop_name,b_shop as b_shop_name,a_warehouse as a_warehouse_name,b_warehouse as b_warehouse_name')
                ->whereTime('createtime', [strtotime($start), strtotime($end)])
                ->order('id desc')
                ->select();
                $data['data'] = [];
                $o = 0;
                foreach ($xxx as $key => $value) {
                    $arr = json_decode($value['product_json'],true);
                    foreach ($arr as $k => $v) {
                        $data['data'][$o]['sn'] = $value['sn'];
                        $data['data'][$o]['a_shop_name'] = $value['a_shop_name'];
                        $data['data'][$o]['a_warehouse_name'] = $value['a_warehouse_name'];
                        $data['data'][$o]['b_shop_name'] = $value['b_shop_name'];
                        $data['data'][$o]['b_warehouse_name'] = $value['b_warehouse_name'];
                        $data['data'][$o]['bak'] = $value['bak'];
                        switch ($value['status']) {
                            case '1':
                                $data['data'][$o]['status'] = '待审核';
                                break;
                            case '2':
                                $data['data'][$o]['status'] = '通过';
                                break;
                            case '3':
                                $data['data'][$o]['status'] = '不通过';
                                break;
                        }
                        $data['data'][$o]['createtime'] = $value['createtime'];
                        $data['data'][$o]['name'] = $v['name'];
                        $data['data'][$o]['specs'] = $v['specs'];
                        $data['data'][$o]['unit_text'] = $v['unit_text'];
                        $data['data'][$o]['supplier_text'] = $v['supplier_text'];
                        $data['data'][$o]['num'] = $v['num'];
                        $data['data'][$o]['pbak'] = isset($v['bak']) ? $v['bak'] :'';
                        $o++;
                    }
                   
                }
            }else{
                $data['data'] = AllocationModel::where($where)
                ->field('*, a_shop as a_shop_name,b_shop as b_shop_name,a_warehouse as a_warehouse_name,b_warehouse as b_warehouse_name')
                ->whereTime('createtime', [strtotime($start), strtotime($end)])
                ->page($page)
                ->limit($limit)
                ->order('id desc')
                ->select();
            }
            
            $data['count'] = AllocationModel::where($where)->whereTime('createtime', [strtotime($start), strtotime($end)])->count('id');
            $data['code'] = 0;
            return json($data);

        }
        $wares = WarehouseModel::all()->toArray();
        $this->assign('wares', $wares);

        $this->assign('shop_id', session('shop_id'));
        return $this->fetch();
    }
    public function add()
    {
        $sn = create_order_sn();
        $this->assign('sn',$sn);
         $admins = Db::name('system_user')
        ->field('id,nick')
        ->select();
        $this->assign('admins', $admins);
        $shop2 = $shops = Db::name('shop')->field('id as value,name as label')->select();
        foreach ($shops as $key => $value) {
            $shops[$key]['children'] = Db::name('warehouse')->field('id as value, name as label')->where('shop_id',$value['value'])->select();
            $shop2[$key]['children'] = Db::name('warehouse')->field('id as value, name as label')->where('shop_id',$value['value'])->where('type',0)->select();
        }
        $this->assign('warehouses2', $shop2);
        $this->assign('warehouses', $shops);
        $products = ProductModel::field('*,supplier_id as supplier_text,unit_id as unit_text, id as product_id')->where('status',1)->all();
        $this->assign('products',$products);
        return $this->fetch('add');
    }

    public function addDo()
    {
        $postData = $this->request->post();
        if($postData['a_id'] == ''){
            return $this->axiosMsg('操作人为必填项',false);
        }
        if($postData['a_shop_warehouse'] == ''){
            return $this->axiosMsg('调出仓库为必填项',false);
        }
         if($postData['b_shop_warehouse'] == ''){
            return $this->axiosMsg('调入仓库为必填项',false);
        }
        if(empty($postData['product'])){
            return $this->axiosMsg('没有产品提交',false);
        }

        $asw = $postData['a_shop_warehouse'];
        $bsw = $postData['b_shop_warehouse'];
        unset($postData['a_shop_warehouse']);
        unset($postData['b_shop_warehouse']);

        $postData['a_shop'] = $asw[0];
        $postData['a_warehouse'] = $asw[1];
        $postData['b_shop'] = $bsw[0];
        $postData['b_warehouse'] = $bsw[1];

        $postData['product_json'] = json_encode($postData['product']);
        if(AllocationModel::create($postData) === false){
            return $this->axiosMsg('创建失败',false);
        }
        return $this->axiosMsg('创建成功！',true);
    }

    public function look()
    {
        $type = $this->request->param('type',1);
        $id = $this->request->param('id','');
        if($id == ''){
            $this->error('调拨单不存在！');
        }
        $Purchase = AllocationModel::get($id);
        $products = json_decode($Purchase->product_json,true);
        $zong = 0;
        foreach ($products as $key => $value) {
            $products[$key]['jine'] = $value['price1'] * $value['num'];
            $zong += $products[$key]['jine'];
        }
        $admins = Db::name('system_user')
        ->field('id,nick')
        ->select();
        $this->assign('admins', systemUserModel::getSelect($admins));
        $this->assign('zong', $zong);
        $this->assign('products', $products);
        $this->assign('id',$id);
        $this->assign('type',$type);
        return $this->fetch();
    }

    public function edit()
    {
        $id = $this->request->param('id','');
        $type = $this->request->param('type',1);
        if($id == ''){
            return $this->error('数据不存在');
        }
        $formData = AllocationModel::get($id);
        $this->assign('formData',$formData);
        $tableDate = $formData->product_json;
        $this->assign('tableDate',json_decode($tableDate));

        $admins = Db::name('system_user')
        ->field('id,nick')
        ->select();
        $this->assign('admins', $admins);
        $shops = Db::name('shop')->field('id as value,name as label')->select();
        foreach ($shops as $key => $value) {
            $shops[$key]['children'] = Db::name('warehouse')->field('id as value, name as label')->where('shop_id',$value['value'])->select();
        }
        $this->assign('warehouses', $shops);
        $products = ProductModel::field('*,supplier_id as supplier_text,unit_id as unit_text, id as product_id')->where('status',1)->all();
        $this->assign('products',$products);
        if(!is_empty($this->request->param('xx')) && $this->request->param('xx') == 2){
            $this->view->engine->layout(false);
            $formData['a_shop_n'] = Db::name('shop')->where('id',$formData['a_shop'])->value('name');
            $formData['b_shop_n'] = Db::name('shop')->where('id',$formData['b_shop'])->value('name');
            $formData['b_w_n'] = Db::name('warehouse')->where('id',$formData['b_warehouse'])->value('name');
            $formData['a_w_n'] = Db::name('warehouse')->where('id',$formData['a_warehouse'])->value('name');
            $this->assign('formData',$formData);
            return $this->fetch('dayin');
        }
        return $this->fetch('edit');
    }

    public function editDo()
    {
        $postData = $this->request->post();
        if($postData['a_id'] == ''){
            return $this->axiosMsg('操作人为必填项',false);
        }
        if($postData['a_shop_warehouse'] == ''){
            return $this->axiosMsg('调出仓库为必填项',false);
        }
         if($postData['b_shop_warehouse'] == ''){
            return $this->axiosMsg('调入仓库为必填项',false);
        }
        if(empty($postData['product'])){
            return $this->axiosMsg('没有产品提交',false);
        }

        $asw = $postData['a_shop_warehouse'];
        $bsw = $postData['b_shop_warehouse'];
        unset($postData['a_shop_warehouse']);
        unset($postData['b_shop_warehouse']);

        $postData['a_shop'] = $asw[0];
        $postData['a_warehouse'] = $asw[1];
        $postData['b_shop'] = $bsw[0];
        $postData['b_warehouse'] = $bsw[1];
        $postData['status'] = 1;
        // $products = $postData['product'];
        $postData['product_json'] = json_encode($postData['product']);
        try {
            AllocationModel::update($postData);
        } catch (Exception $e) {
            return $this->axiosMsg($e->getMessage(), false);
        }

        return $this->axiosMsg('保存成功！',true);
    }
    public function check()
    {
        $id = $this->request->param('id','');
        $type = $this->request->param('type',1);
        if($id == ''){
            return $this->error('数据不存在');
        }
        $formData = AllocationModel::get($id);
        $this->assign('formData',$formData);
        $tableDate = $formData->product_json;
        $this->assign('tableDate',json_decode($tableDate));

        $admins = Db::name('system_user')
        ->field('id,nick')
        ->select();
        $this->assign('admins', $admins);
        $shops = Db::name('shop')->field('id as value,name as label')->select();
        foreach ($shops as $key => $value) {
            $shops[$key]['children'] = Db::name('warehouse')->field('id as value, name as label')->where('shop_id',$value['value'])->select();
        }
        $this->assign('warehouses', $shops);
        $products = ProductModel::field('*,supplier_id as supplier_text,unit_id as unit_text, id as product_id')->where('status',1)->all();
        $this->assign('products',$products);
        return $this->fetch();
    }
    public function checkDo()
    {

            $formData =$this->request->param();

            if($formData['id'] == ''){
                return $this->axiosMsg('订单不存在',false);
            }
            $formData['b_id'] = ADMIN_ID;
 
            Db::startTrans();
            try {
                if($formData['val'] == 2){
                    $info = Db::name('allocation')->where('id',$formData['id'])->find();

                    // $products = json_decode($info['product_json'], true);
                    $products = $formData['product'];
                   
                    $out = [];
                    $in = [];
                    $wareType = Db::name('warehouse')->where('id',$info['b_warehouse'])->value('type');
                    $StockModel = new StockModel;
                    foreach ($products as $key => $value) {
                        $begin_num_a = $StockModel->getBeginNum($info['a_warehouse'],$value['product_id']);
                        $begin_price_a = $StockModel->getBeginPrice($info['a_warehouse'],$value['product_id']);
                        $end_price_a = $begin_price_a;
                       $out[] = [
                            'product_id'  =>  $value['product_id'],
                            'product_num'  =>  $value['num'],
                            'product_name'  =>  $value['name'],
                            'shop_id'  =>  $info['a_shop'],
                            'sn'  =>  $info['sn'],
                            'type'  =>  '出库',
                            'detailed_type'  => 3,
                            // 'user_id'  =>  ,
                            'warehouse_id'  => $info['a_warehouse'] ,
                            'createtime'  => time() ,
                            'status'  => 1 ,
                            'bak'  => isset($value['bak']) ? $value['bak'] : '' ,
                            'updatetime'  => time() ,
                            'unit_price'  => $value['num'] * $value['price1'],
                            'price'       => $value['num'] * $value['price1'],
                            'begin_num'   => $begin_num_a,
                            'end_num'     => $begin_num_a - $value['num'],
                            'begin_price' => $begin_price_a,
                            'end_price'   => $end_price_a,
                        ]; 
                        if($wareType == 1){   // 配料库
                            $begin_num_b = $StockModel->getBeginNum($info['b_warehouse'],$value['product_id']);
                            $begin_price_b = $StockModel->getBeginPrice($info['b_warehouse'],$value['product_id']);
                            $end_price_b = $begin_price_b;
                            $in[] = [
                                'product_id'  =>  $value['product_id'],
                                'product_num'  =>  $value['num'] * $value['specs'],
                                'product_name'  =>  $value['name'],
                                'shop_id'  =>  $info['b_shop'],
                                'sn'  =>  $info['sn'],
                                'type'  =>  '入库',
                                'detailed_type'  => 5,
                                // 'user_id'  =>  ,
                                'warehouse_id'  => $info['b_warehouse'] ,
                                'createtime'  => time() ,
                                'status'  => 1 ,
                                'bak'  => isset($value['bak']) ? $value['bak'] : '' ,
                                'updatetime'  => time() ,
                                'unit_price'  => $value['num'] * $value['price1'] ,
                                'price'       => $value['num'] * $value['price1'] ,
                                'begin_num'   => $begin_num_b,
                                'end_num'     => $begin_num_b + $value['num'] * $value['specs'],
                                'begin_price' => $begin_price_b,
                                'end_price'   => $end_price_b,
                            ];
                        }else{
                            $begin_num_b = $StockModel->getBeginNum($info['b_warehouse'],$value['product_id']);
                            $begin_price_b = $StockModel->getBeginPrice($info['b_warehouse'],$value['product_id']);
                            $end_price_b = $begin_price_b;
                            $in[] = [
                                'product_id'  =>  $value['product_id'],
                                'product_num'  =>  $value['num'],
                                'product_name'  =>  $value['name'],
                                'shop_id'  =>  $info['b_shop'],
                                'sn'  =>  $info['sn'],
                                'type'  =>  '入库',
                                'detailed_type'  => 5,
                                // 'user_id'  =>  ,
                                'warehouse_id'  => $info['b_warehouse'] ,
                                'createtime'  => time() ,
                                'status'  => 1 ,
                                'bak'  => isset($value['bak']) ? $value['bak'] : '' ,
                                'updatetime'  => time() ,
                                'unit_price'  => $value['num'] * $value['price1'],
                                'price'       => $value['num'] * $value['price1'],
                                'begin_num'   => $begin_num_b,
                                'end_num'     => $begin_num_b + $value['num'],
                                'begin_price' => $begin_price_b,
                                'end_price'   => $end_price_b,
                            ];
                        }

                    }
                    Db::name('stock')->insertAll($out);
                    Db::name('stock')->insertAll($in);
                }
                Db::name('allocation')->where('id',$formData['id'])->update(['status'=>$formData['val']]);
                 // 提交事务 38322
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->axiosMsg($e->getMessage(), false);
            }

            return $this->axiosMsg('审核成功！',true);
    }

}
